package com.mayikt.aop.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @Name PoliceGlobalExceptionHandler
 * @Author 枫火
 * @Date 2021/7/13 7:53
 * @Description
 **/
@ControllerAdvice
public class PoliceGlobalExceptionHandler extends BaseApiService {

    @Value("${spring.application.name}")
    private String serverIdName;
    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public BaseResponse<String> errorResult(HttpServletRequest request, Exception ex) throws UnknownHostException {
        // 采用全局捕获异常 拦截系统中的错误，返回友好的提示给客户端
        Map<String, String[]> parameterMap = request.getParameterMap();
        StackTraceElement[] stackTrace = ex.getStackTrace();
        StackTraceElement stackTraceElement = stackTrace[0];
        // 转换成json
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(stackTraceElement));
        // 新增参数内容
        jsonObject.put("parameterContent", parameterMap);
        // 新增错误日志
        jsonObject.put("errorContent", ex.getMessage());
        jsonObject.put("serviceId", serverIdName);
        jsonObject.put("createTime", new Date());
        jsonObject.put("messageId", UUID.randomUUID().toString().replace("-", ""));
        // 获取ip地址
        jsonObject.put("serverIp", getServerAddress());
        // 投递到kafka中
        send(jsonObject);
        return setResultError("系统错误");
    }

    /**
     * 发送消息的方法
     *
     * @param data 推送数据的data
     */
    private void send(JSONObject data) {
        // topic 名称 key data 消息数据
        kafkaTemplate.send("mayikt-topic-log", null, data.toJSONString());
    }

    private String getServerAddress() throws UnknownHostException {
        InetAddress ip4 = Inet4Address.getLocalHost();
        return ip4.getHostAddress() + ":" + serverPort;
    }
}
